package com.healthcarex.hip.saas.oauth2config.store;

import com.healthcarex.hip.saas.oauth2config.constant.SecurityConstants;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;
import org.springframework.security.oauth2.provider.token.store.JwtTokenStore;
import org.springframework.security.oauth2.provider.token.store.KeyStoreKeyFactory;
import org.springframework.security.oauth2.provider.token.store.redis.RedisTokenStore;

import javax.annotation.Resource;
import java.security.KeyPair;

/**
 * @date: 2018/1/20
 * @description: 授权服务器 TokenStore 配置类，使用 JWT RSA 非对称加密
 */
public class AuthRsaJwtTokenStore {

    @Autowired
    private JwtProperties jwtProperties;

    @Bean("keyProp")
    public KeyProperties keyProperties() {
        return new KeyProperties();
    }

    @Resource(name = "keyProp")
    private KeyProperties keyProperties;

    @Autowired(required = false)
    private RedisConnectionFactory redisConnectionFactory;

    @Bean
    public TokenStore tokenStore(JwtAccessTokenConverter jwtAccessTokenConverter) {
        if ("Redis".equalsIgnoreCase(jwtProperties.getTokenStore())) {
            RedisTokenStore tokenStore = new RedisTokenStore(redisConnectionFactory);
            tokenStore.setPrefix(SecurityConstants.PREFIX);
            return tokenStore;
        }
        return new JwtTokenStore(jwtAccessTokenConverter);
    }

    @Bean
    public JwtAccessTokenConverter jwtAccessTokenConverter() {
        JwtAccessTokenConverter converter = new JwtAccessTokenConverter();
        KeyPair keyPair = new KeyStoreKeyFactory
                (keyProperties.getLocation(), keyProperties.getSecret().toCharArray())
                .getKeyPair(keyProperties.getAlias());
        converter.setKeyPair(keyPair);
        return converter;
    }

}
